package gl.android.biyiqing.fragment;

import gl.adapter.BaseFragmentPagerAdapter;
import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.GiftActivity;
import gl.android.biyiqing.R;
import gl.android.biyiqing.api.API;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.func.updoladPicture.SelectPictureActivity;
import gl.func.updoladPicture.TakePicSucess;
import gl.func.updoladPicture.Upload;
import gl.uitls.Lg;
import gl.uitls.Tip;
import gl.view.TabIndictor;

import java.io.File;
import java.util.ArrayList;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import de.greenrobot.event.EventBus;

public class MineFragment extends BaseFragment {
	// Content View Elements

	// Content View Elements

	private ImageView imageView1;
	private View imageView2;
	private View imageView3;
	private RadioGroup mRadioGroup;
	private android.support.v4.view.ViewPager pager;
	private View cousr;
	private ImageView iv_buygift;

	OnClickListener uploadalbum = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			SelectPictureActivity.pickImage(getActivity(),
					SelectPictureActivity.REQUESTCODE_TAKE_ALBUM);
		}
	};
	OnClickListener uploadavator = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			SelectPictureActivity.pickImage(getActivity(),
					SelectPictureActivity.REQUESTCODE_TAKE_AVATOR);
		}
	};
	OnClickListener sign = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			BaseControl.get(API.URL + "SetSignin?userid=%s",
					new AjaxCallBackProxy() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							try {
								final JSONObject jsonObject = new JSONObject(t);
								if ("2".equals(jsonObject.getString("msg"))) {
									Tip.show("签到成功");
								}
								else if ("3".equals(jsonObject.getString("msg"))) {
									Tip.show("已经签到");
								}
								else {
									Tip.show("签到失败");
								}
							} catch (Exception e) {
								e.printStackTrace();
								onFailure(e, 0, e.getMessage());
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							Tip.show("签到失败");
						}
					}, new Object[] { UserManger.getInstance().userid });
		}
	};
	OnClickListener buy = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			goBuyActy(getActivity());
		}
	};
	OnClickListener myaccount = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getActivity(),
					FragmentContainerActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
					MyAccountFragment.class.getName());
			intent.putExtras(bundle);
			getActivity().startActivity(intent);
		}
	};
	OnClickListener mybuy = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getActivity(),
					FragmentContainerActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
					ShopFragment.class.getName());
			intent.putExtras(bundle);
			getActivity().startActivity(intent);
		}
	};

	public void goBuyActy(Context context) {
		Intent intent = new Intent(context, FragmentContainerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
				ShopFragment.class.getName());
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

	private void bindViews() {

		imageView1 = (ImageView) rootView.findViewById(R.id.imageView1);
		imageView1.setOnClickListener(uploadavator);
		imageView2 = (View) rootView.findViewById(R.id.imageView2);
		imageView2.setOnClickListener(uploadavator);
		imageView3 = (View) rootView.findViewById(R.id.imageView3);
		imageView3.setOnClickListener(sign);
		rootView.findViewById(R.id.radio0).setOnClickListener(buy);
		iv_buygift = (ImageView) rootView.findViewById(R.id.iv_buygift);
		iv_buygift.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), GiftActivity.class);
				Bundle args = new Bundle();
				args.putString(KEY_TO_USER_ID, userID);
				intent.putExtras(args);
				startActivity(intent);
			}
		});
		findViewById(R.id.radio1).setOnClickListener(myaccount);
		findViewById(R.id.radio0).setOnClickListener(mybuy);
		mRadioGroup = (RadioGroup) rootView.findViewById(R.id.RadioGroup);
		cousr = (View) rootView.findViewById(R.id.indr_bottom);
		pager = (android.support.v4.view.ViewPager) rootView
				.findViewById(R.id.pager);
	}

	public MineFragment() {
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		EventBus.getDefault().unregister(this);
	}

	final String type_avator = "1-";
	final String type_album = "2-";

	class AjaxCallBackForUpload extends AjaxCallBack<String> {
		String temp_type;

		AjaxCallBackForUpload(String type) {
			temp_type = type;
		}

		final String UPLOADFAIL = "上传失败";

		@Override
		public void onLoading(long count, long current) {
			super.onLoading(count, current);
			System.out.println(current + "/" + count);
		}

		@Override
		public void onSuccess(String t) {
			super.onSuccess(t);
			Lg.i(t);
			try {
				if (!new JSONObject(t).getBoolean("ret")) {
					Tip.show(UPLOADFAIL);
				}
				else {
					Tip.show("上传成功");
					if (temp_type == type_album) {
						// EventBus.getDefault().post(
						// new RefreshAlbum(
						// UserManger.getInstance().userid));
						initData();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				onFailure(e, 0, "");
			}
		}

		@Override
		public void onFailure(Throwable t, int errorNo, String strMsg) {
			super.onFailure(t, errorNo, strMsg);
			Tip.show(UPLOADFAIL + t.getMessage());
		}
	};

	public void onEvent(final TakePicSucess take) {
		if (isValueFragment()) {

			String type = "1-";

			if (take.getRequestCode() == SelectPictureActivity.REQUESTCODE_TAKE_AVATOR) {
				type = type_avator;
				Tip.show("正在上传头像");
				// App.mFBitmap.display(imageView1, "file:///" +
				// take.getPath()[0]);
				// imageView1.setImageBitmap(BitmapFactory.decodeFile(take.getPath()[0]));
				ImageLoader.getInstance().displayImage(
						"file:///" + take.getPath()[0], imageView1, listener);
			}
			else if (take.getRequestCode() == SelectPictureActivity.REQUESTCODE_TAKE_ALBUM) {
				type = type_album;
				Tip.show("正在上传相片");
			}

			for (String paths : take.getPath()) {
				Upload.uploadFile(type + UserManger.getInstance().userid
						+ ".jpg", new File(paths), new AjaxCallBackForUpload(
						type));
			}
		}

	}

	final ImageLoadingListener listener = new ImageLoadingListener() {
		@Override
		public void onLoadingStarted(String imageUri, View view) {
		}

		@Override
		public void onLoadingFailed(String imageUri, View view,
				FailReason failReason) {
		}

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			((ImageView) view).setImageBitmap(loadedImage);
		}

		@Override
		public void onLoadingCancelled(String imageUri, View view) {
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		EventBus.getDefault().register(this);
		rootView = inflater.inflate(R.layout.fragment_mime, container, false);
		bindViews();
		initData();
		return rootView;
	}

	private void initData() {

		BaseControl.get(API.URL + "GetUserInfo?userid=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						if (!isValueFragment()) {
							return;
						}
						super.onSuccess(t);
						try {
							if (new JSONObject(t).getJSONArray("data") == null) {
								return;
							}

							AlbumFragment albumFragment = null;
							if (MineFragment.this.getChildFragmentManager()
									.getFragments() != null) {
								for (Fragment iterable_element : MineFragment.this
										.getChildFragmentManager()
										.getFragments()) {
									if (iterable_element instanceof AlbumFragment) {
										albumFragment = (AlbumFragment) iterable_element;
									}
								}
							}
							Object userphoto = new JSONObject(t)
									.get("userphoto");

							if (albumFragment != null) {
								albumFragment.refresh(userphoto);
							}
							else {
								albumFragment = (AlbumFragment) BaseFragment
										.creatBaseFramgent(userID,
												userphoto.toString(),
												AlbumFragment.class);
							}
							ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();

							fragmentList.add(albumFragment);

							JSONObject data = new JSONObject(t).getJSONArray(
									"data").optJSONObject(0);

							if (data == null) {
								return;
							}
							// App.mFBitmap.display(imageView1, API.IMAGEURL
							// + data.getString("avatar"));
							ImageLoader.getInstance().displayImage(
									API.IMAGEURL + data.getString("avatar"),
									imageView1, listener);
							
							TextView name = (TextView) findViewById(R.id.name);
							name.setText(data.optString("username"));
							UserManger.getInstance().username = data.optString("username");
							fragmentList.add(BaseFragment.creatBaseFramgent(
									userID, data.toString(),
									UserInfoFragment.class));
							fragmentList.add(BaseFragment.creatBaseFramgent(
									userID, data.toString(),
									WangLaiFragment.class));

							pager.setAdapter(new BaseFragmentPagerAdapter(
									MineFragment.this.getChildFragmentManager(),
									fragmentList));
							new TabIndictor(getActivity(), pager, mRadioGroup,
									cousr);
						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}
				}, userID);

	}
}
